#include <SFML/Graphics.hpp>
#include <iostream>
#include "include/Scene.hpp"
#include "line.hpp"
#include  "canvas.hpp"
using namespace  std;
using namespace sf;
//
const int SCREEN_WIDTH = 600;
const int SCREEN_HEIGHT = 600;

float viewportSizeX = 1.0;
float viewportSizeY = 1.0;
float projectionPlanD = 1.0;
sf::VertexArray vertices;
Vector2f transformCoord(const Vector2f& coord, Vector2f v = Vector2f(1, 1), int d = 1)
{

    float x = SCREEN_WIDTH / 2 + coord.x;
    float y = SCREEN_HEIGHT / 2 - coord.y - 1;
    return {x, y};
}

void putPixel(const Vector2f& coord, sf::Color color)
{
    auto res = transformCoord(coord);
    const Vertex vertex = {
        .position = res,
        .color = color
    };
    vertices.append(vertex);
}

Vector3f canvaseToViewPort(float x, float y)
{
    return {
        x * viewportSizeX / SCREEN_WIDTH, y * viewportSizeY / SCREEN_HEIGHT, projectionPlanD
    };
}

int main() {

    vertices.setPrimitiveType(sf::PrimitiveType::Points);
    vertices.resize(SCREEN_WIDTH * SCREEN_HEIGHT);
    vertices.clear();
    // cout << (INFINITY < INFINITY) << endl;
    sf::RenderWindow window(sf::VideoMode({SCREEN_WIDTH, SCREEN_HEIGHT}), "My window");
    window.setFramerateLimit(60);
    const Vector3f origin = {0, 0, 0};
    Scene scence;
    for (int x = -SCREEN_WIDTH / 2; x < SCREEN_WIDTH / 2; x++) {
        for (int y = -SCREEN_HEIGHT / 2; y < SCREEN_HEIGHT / 2; y++) {
            auto direction = canvaseToViewPort(x, y);
            // cout << direction.x << " " << direction.y << "\n";
            auto c = scence.traceRay(origin, direction, 1, INFINITY, 3);
            putPixel({x * 1.f, y * 1.f}, c);
        }
    }

    Vector2f p0 = {-100, -100};
    Vector2f p1 = {100, 100};
    Canvas canvas(SCREEN_WIDTH, SCREEN_HEIGHT);
    // canvas.drawLine(p0, p1, sf::Color::Blue);
    canvas.drawFilledTriangle({-200, -250}, {200, 50}, {20, 250}, sf::Color::Green);
    while (window.isOpen()) {

        while (auto e = window.pollEvent()) {
            if (e->is<Event::Closed>()) {
                window.close();
            }
        }
        // clear the window with black color
        window.clear(sf::Color::Black);
        // draw everything here...
        window.draw(canvas.getScreenPixel());
        // window.draw(vertices);
        // end the current frame
        window.display();
    }
    return 0;
}